class ArticlesController < ApplicationController
  def new
    @article = Article.new #如果这里不这么做的话，再视图中@article的值为nil,再获取错误信息时会出错。
  end
  def create
    params.permit!
    #初始化
    @article = Article.new(article_params)
    #将模型保存至数据库
    if @article.save
      redirect_to @article
    else
      render 'new'  #render类似于java中的转发
    end
    #render plain: params[:article].inspect
  end

  private
  def article_params
    params.require(:article).permit(:title, :text)
  end

  public #此处与教程不同，这里需要手动改为public
  def show
    @article = Article.find(params[:id])

  end
  #显示全部
  def index
    @articles = Article.all
  end

  #更新文章
  def edit
    @article = Article.find(params[:id])
  end

  def update
    @article = Article.find(params[:id])
    if @article.update(article_params)
      redirect_to @article
    else
      render 'edit'
    end
  end

  def destroy
    @article = Article.find(params[:id])
    @article.destroy
    redirect_to articles_path
  end
end
